import {
  md5
} from 'vux'
import axios from 'axios'
import Qs from 'qs' //qs一般装了axios就自带不用再装，如果没有，自己安装下
import moment from 'moment' //导入文件
  let instance = axios.create({
  baseURL: '', //这里配置你自己的url
    transformRequest: [function (data) {
      data = Qs.stringify(data) //序列化参数
      return data
    }],
    withCredentials: true // 允许携带cookie
  })
  let pending = []; //声明一个数组用于存储每个ajax请求的取消函数和ajax标识

  let cancelToken = axios.CancelToken;

  let removePending = (config) => {
    for (let p in pending) {
      if (config.remove) { //当当前请求在数组中存在时执行函数体
        pending[p].f(); //执行取消操作
        pending.splice(p, 1); //把这条记录从数组中移除
      }
    }
  }
  //添加请求拦截器
  instance.interceptors.request.use(config => {
    removePending(config); //在一个ajax发送前执行一下取消操作
    config.cancelToken = new cancelToken((c) => {
      //这里的ajax标识我是用请求地址&请求方式拼接的字符串，当然你可以选择其他的一些方式
      if (config.remove) {
        pending.push({
          u: config.url + '&' + config.method,
          f: c
        });
      }
    });
    return config;
  }, error => {
    return Promise.reject(error);
  });
  //添加响应拦截器
  instance.interceptors.response.use(res => {
    removePending(res.config); //在一个ajax响应后再执行一下取消操作，把已经完成的请求从pending中移除
    //登出 if(res.data&&(res.data.UserNotLogin == 1||(res.data.FixError&&res.data.FixError.includes('FIX-20012')))){
    //    router.push('/')
    //    Vue.$vux.toast.text('登录超时，请重新登录','middle')
    // }
    return res;
  }, error => {
    return {
      data: {
        errmsg: error.message
      }
    };
  });
  export default instance;

  //按服务器拼接获取task详细信息请求的参数
  export const getTaskParams = (obj) => {
    let configs = JSON.parse(obj.DATACONFIGS);
    let workItemId = obj.TASKID;//obj.WrkID;
    let keyid = obj.BIZKEY;//obj.KeyID;
    let defKey = obj.DEFKEY;//obj.defKey;
    let FlowID = obj.INSTID;//obj.FlowID;
    let nodeId = obj.NODEID;//obj.nodeId;
    // let defId = obj.defId;

    let formId = configs.formId; //表单id
    let bizObjId = configs.bizObjId; //业务对象
    let formId_Detail = configs.detailObjIds; //明细表业务对象
    let vDetail = "";
    if (formId_Detail == "") {
      vDetail = "";
    } else {
      vDetail = ',"' + formId_Detail.replace(/,/g, "\",\"") + '"  ';
    }
    return '{"_method": "formService.getFormData",  ' +
      '"requestEventData": {' +
      '    "eventType": "formInitEvent", ' +
      '    "formType": 1,  ' +
      '    "bizObjId": "' + bizObjId + '",  ' +
      '    "formId": "' + formId + '"  ' +
      '},' +
      '"useType": "modify",  ' +
      '"getData": {' +
      '    "useType": "modify",  ' +
      '    "objName": "' + bizObjId + '",  ' +
      '    "relatedObj": [' +
      '        "' + bizObjId + '"  ' +
      vDetail +
      '    ],' +
      '    "pk": [' +
      '        {' +
      '            "key": "GUID",  ' +
      '            "value": "' + keyid + '" ' //任务待办的KeyID  b
      +
      '        }' +
      '    ]' +
      '},' +
      '"getToolbar": {' +
      '    "useType": "modify",  ' +
      '    "objName": "' + bizObjId + '", ' +
      '    "viewId": "' + formId + '",  ' +
      '    "defId": "' + encodeURIComponent(keyid) + '", ' //任务待办的defId
      +
      '    "defKey": "' + defKey + '", ' //任务待办的defKey   
      +
      '    "instId": "' + FlowID + '", ' //任务待办的FlowID   
      +
      '    "taskId": "' + workItemId + '", ' //任务待办的WrkID  
      +
      '    "nodeId": "' + nodeId + '" ' //任务待办的nodeId
      +
      '}' + '}'
  }

  export const getRiskParams = (obj, taskListIng) => {
    let configs = JSON.parse(obj.DATACONFIGS);
    let keyid = obj.GUID;//obj.KeyID;

    let formId = configs.formId; //表单id
    let bizObjId = configs.bizObjId; //业务对象
    let formId_Detail = configs.detailObjIds; //明细表业务对象
    let vDetail = "";
    if (formId_Detail == "") {
      vDetail = "";
    } else {
      vDetail = ',"' + formId_Detail.replace(/,/g, "\",\"") + '"  ';
    }
    return '{"_method": "formService.getFormData",  ' +
      '"requestEventData": {' +
      '    "eventType": "formInitEvent", ' +
      '    "formType": 1,  ' +
      '    "bizObjId": "' + bizObjId + '",  ' +
      '    "formId": "' + formId + '"  ' +
      '},' +
      '"useType": "modify",  ' +
      '"getData": {' +
      '    "useType": "modify",  ' +
      '    "objName": "' + bizObjId + '",  ' +
      '    "relatedObj": [' +
      '        "' + bizObjId + '"  ' +
      vDetail +
      '    ],' +
      '    "pk": [' +
      '        {' +
      '            "key": "GUID",  ' +
      '            "value": "' + keyid + '" ' //任务待办的KeyID  b
      +
      '        }' +
      '    ]' +
      '},' +
      '"getSysVar": {'+
      '"now":"{sysDate.Now}",'+
      '"test_2":"{sysLoginUser.username}",'+
      '"INPUTERNAME": "{sysLoginUser.loginId}",  ' +
      '"PHONENUM": "{sysLoginUser.tel}",  ' +
      '"INPUTERDEPTNAME": "{sysLoginUser.orgName}",' +
      '"INPUTERDEPTPATHID": "{sysLoginUser.orgPathId}",' +
      '"text_0": "{sysDate.Today}",' +
      '},' +
      '"getFormVerify": {'+
      '    "objName": "' + bizObjId + '", ' +
      '    "viewId": "' + formId + '",  ' +
      '},' +
      '"getToolbar": {' +
      '    "useType": "modify",  ' +
      '    "objName": "' + bizObjId + '", ' +
      '    "viewId": "' + formId + '",  ' +
      '    "defKey": "' + bizObjId + '",  ' +
      '    "defId": "' + keyid + '",  ' +
      '    "instId": "' + taskListIng[0].instId + '",  ' +
      '    "taskId": "' + taskListIng[0].taskId + '",  ' +
      '    "nodeId": "' + taskListIng[0].nodeId + '",  ' +
      '}' + '}'
  } 

  export const pattern = function (fmt) {
    if (!!fmt) {
      fmt = fmt.replace('yyyy', 'YYYY').replace('dd', 'DD').replace('hh', 'HH')
    } else {
      fmt = 'YYYY-MM-DD HH:mm'
    }
    return moment(this).format(fmt)
  }


//重新组织请求url，原始url中不能含参数
//加上token、timestamp、salt、sign
//sign=MD5(token+timestamp+salt+其他参数)
//ExtParams 必须是 a=1&b=2 形式的字符串
export const getReqUrl = (url, ExtParams) => {
  let token = window.localStorage.getItem("token") || "";
  let salt = "EcidiMOASalt";
  var Params = "";
  var timestamp = (new Date()).valueOf();
  Params += "timestamp=" + timestamp + "&token=" + token;
  if (typeof (ExtParams) != "undefined" && ExtParams != "")
    Params = Params + "&" + ExtParams;
  var ParamArr = sortUrlParams(Params);
  ParamArr = objKeySort(ParamArr);
  var paramstr = [];
  for (var i in ParamArr) {
    paramstr.push(i + "=" + ParamArr[i]);
  }
  paramstr = paramstr.join("&");
  var sign = md5(paramstr + "&salt=" + salt);
  //console.log(paramstr);
  return url + "?" + paramstr + "&sign=" + sign;
}
//获取url里的参数，return object
function sortUrlParams(str) {
  if (typeof str !== 'string') {
    return {};
  }
  var paramObj = {};
  var paramArr = decodeURI(str).split('&');
  for (var i = 0; i < paramArr.length; i++) {
    var tmp = paramArr[i].split('=');
    var key = tmp[0];
    var value = tmp[1] || "";
    //if (typeof value === 'string' && isNaN(Number(value)) === false && value !== "") {
    //  value = Number(value);
    //}
    if (typeof paramObj[key] === 'undefined') {
      paramObj[key] = value;
    } else {
      var newValue = Array.isArray(paramObj[key]) ? paramObj[key] : [
        paramObj[key]
      ];
      newValue.push(value);
      paramObj[key] = newValue;
    }
  }
  return paramObj;
}
//Object排序
function objKeySort(obj) {
  var newkey = Object.keys(obj).sort();
  var newObj = {};
  for (var i = 0; i < newkey.length; i++) {
    newObj[newkey[i]] = obj[newkey[i]];
  }
  return newObj;
}

// //按服务器拼接参数
// export const getTaskParams = (item)=>{
//   if(item.WEBNAME){
//       switch(item.WEBNAME){
//         case "purchasesubsys":return "_objName=PUR_PLAN&_defKey=Pur_Plan&_defId=Pur_Plan%25253A1%25253Aac43a8c0-3450-47d3-b7c7-751fcbe4c896&_instId=16e2d05c-f88b-4fe8-9d4b-f82744e0aa6a&_taskId=09ad2e34-f776-4780-8b7f-2fbb177fb052&_nodeId=UserTask_4&_nodeName=%252525E9%252525A1%252525B9%252525E7%2525259B%252525AE%252525E7%252525BB%2525258F%252525E7%25252590%25252586%252525E5%252525AE%252525A1%252525E6%2525259F%252525A5&_agent=&_pk=GUID&_pkValue=1523584846063100218919&_useType=modify&sysform=1"
//       }
//   }else{
//     return "";
//   }
// }



//生成guid
export const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    let r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

//数组转换成树
export const toTree = (data, _this) => {
  // 删除 所有 children,以防止多次调用
  data.forEach(function (item) {
    delete item.children;
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  let map = {};
  data.forEach(function (item) {
    map[item.ID] = item;
  });
  // console.log(map);

  let val = [];
  data.forEach(function (item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    let parent = map[item.PARENTID];

    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  data.forEach((item) => {
    // if(this.type == 'person'){
    if (!item.children) {
      // getPersonByDept(item, _this)
    }
    // }else{
    //   item.leaf = true
    // }
  })
  return val;
}
//获取人员并放入部门下
function getPersonByDept (item, _this) {
  if (item.children) {
    return false;
  }
  _this.getPerson(item.ID, '', (res) => {
    if (res.data.data) {
      let personList = res.data.data
      personList.forEach((item) => {
        item.leaf = true
      })
      _this.$set(item, 'children', personList)
    }
  })
}

export const downloadFile = (url, name) => {
  // window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,  (fs)=> {

  // console.log('打开的文件系统: ' + fs.name);
  // fs.root.getFile(this.fileName, { create: true, exclusive: false },
  // (fileEntry)=> {
  let fileUrl = cordova.file.dataDirectory + name
  let fileTransfer = new FileTransfer();
  fileTransfer.download(
    url, fileUrl, (entry) => {
      entry.file(data => {
        console.log(data)
        cordova.plugins.fileOpener2.open(fileUrl, data.type,
          {
            error: function (e) {
              console.log('Error status: ' + e + ' - Error message: ' + e);
            },
            success: function () {
              console.log('open successfully');
            }
          }); // showOpenWithDialog使用手机上安装的程序打开下载的文件
      });
      console.log("download complete: " + entry.toURL());
    },
    (error) => {
      console.log("download error source " + error.source);
      console.log("download error target " + error.target);
      console.log("download error code" + error.code);
    },

    false, {
    }
  )
  // }, ()=>{})}, ()=>{});
}